<template>
    <div class="asset-tree-list">
      <!-- 搜索栏复用 -->
      <SearchFilters @search="onSearch" />
  
      <!-- 树形设备列表 -->
      <el-table
        :data="treeRows"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children' }"
        v-loading="loading"
        style="margin-top: 10px"
      >
        <el-table-column label="设备名称" min-width="200">
          <template #default="{ row }">
            <el-tag :type="typeColor(row.nodeType)" size="small">
              {{ typeLabel(row.nodeType) }}
            </el-tag>
            <span class="ml8">{{ row.name }}</span>
          </template>
        </el-table-column>
  
        <el-table-column prop="code" label="设备编码" width="160" />
        <el-table-column prop="beType" label="设备类别" width="120" />
        <el-table-column prop="area" label="区域" width="120" />
        <el-table-column prop="model" label="型号" width="120" />
        <el-table-column prop="brand" label="品牌" width="120" />
  
        <!-- 展开备件信息 -->
        <el-table-column label="备件信息">
          <template #default="{ row }">
            <el-table
              v-if="row.spareInfos?.length"
              :data="row.spareInfos"
              border
              size="small"
              style="margin-top: 8px"
            >
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="code" label="编码" />
              <el-table-column prop="stockAvailable" label="当前库存" width="100" />
              <el-table-column prop="stockTotal" label="总库存" width="100" />
            </el-table>
            <span v-else>—</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import { listSbtz } from '@/api/sbtz/sbtz'
  import SearchFilters from './SearchFilters.vue'
  
  const loading = ref(false)
  const treeRows = ref([])
  
  function typeLabel(t) {
    return { SYSTEM:'系统', MACHINE:'母设', MODULE:'子设', COMPONENT:'部件', PART:'零件' }[t] || t
  }
  function typeColor(t) {
    return { SYSTEM:'success', MACHINE:'primary', MODULE:'info', COMPONENT:'warning', PART:'danger' }[t] || ''
  }
  
  async function onSearch(params) {
    loading.value = true
    const { rows = [] } = await listSbtz({ ...params, pageNum: 1, pageSize: 1000 })
    // 转树结构
    const map = new Map()
    rows.forEach(r => map.set(r.id, { ...r, children: [] }))
    const roots = []
    rows.forEach(r => {
      const pid = r.parentId || 0
      if (pid === 0) roots.push(map.get(r.id))
      else map.get(pid)?.children.push(map.get(r.id))
    })
    treeRows.value = roots
    loading.value = false
  }
  </script>
  